const Card = require('../models/Card');
const Exercise = require('../models/Exercise');
const ExerciseGenerator = require('../services/exerciseGenerator');

/**
 * @desc    获取所有知识卡片
 * @route   GET /api/cards
 * @access  私有
 */
const getCards = async (req, res) => {
  try {
    // 支持分页
    const page = parseInt(req.query.page) || 1;
    const limit = parseInt(req.query.limit) || 10;
    const skip = (page - 1) * limit;

    // 支持过滤
    const filter = {};
    if (req.query.chapter) filter.chapter = req.query.chapter;
    
    // 处理难度过滤
    if (req.query.difficulty) {
      // 字符串难度值到数字的映射
      const difficultyMap = {
        'EASY': 2,
        'MEDIUM': 3,
        'HARD': 4
      };
      
      // 如果是字符串难度值，使用映射转换
      if (difficultyMap[req.query.difficulty] !== undefined) {
        filter.difficulty = difficultyMap[req.query.difficulty];
      } else {
        // 尝试直接解析为数字
        const difficultyNum = parseInt(req.query.difficulty);
        if (!isNaN(difficultyNum)) {
          filter.difficulty = difficultyNum;
        }
      }
    }
    
    if (req.query.tags) {
      const tags = req.query.tags.split(',');
      filter.tags = { $in: tags };
    }

    // 支持搜索
    if (req.query.search) {
      filter.$text = { $search: req.query.search };
    }

    // 获取卡片总数
    const total = await Card.countDocuments(filter);

    // 获取卡片
    const cards = await Card.find(filter)
      .select('title content chapter difficulty tags createdAt')
      .sort({ createdAt: -1 })
      .skip(skip)
      .limit(limit);

    res.json({
      cards,
      page,
      pages: Math.ceil(total / limit),
      total
    });
  } catch (error) {
    console.error('获取知识卡片时出错:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

/**
 * @desc    获取单个知识卡片
 * @route   GET /api/cards/:id
 * @access  私有
 */
const getCardById = async (req, res) => {
  try {
    const card = await Card.findById(req.params.id)
      .populate('relatedCards', 'title chapter difficulty');

    if (!card) {
      return res.status(404).json({ message: '卡片不存在' });
    }

    res.json(card);
  } catch (error) {
    console.error('获取知识卡片详情时出错:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

/**
 * @desc    更新知识卡片
 * @route   PUT /api/cards/:id
 * @access  私有
 */
const updateCard = async (req, res) => {
  try {
    const { title, content, difficulty, tags } = req.body;
    const card = await Card.findById(req.params.id);

    if (!card) {
      return res.status(404).json({ message: '卡片不存在' });
    }

    // 更新卡片信息
    if (title) card.title = title;
    if (content) card.content = content;
    
    // 处理难度值
    if (difficulty !== undefined) {
      // 字符串难度值到数字的映射
      const difficultyMap = {
        'EASY': 2,
        'MEDIUM': 3,
        'HARD': 4
      };
      
      // 如果是字符串难度值，使用映射转换
      if (typeof difficulty === 'string' && difficultyMap[difficulty] !== undefined) {
        card.difficulty = difficultyMap[difficulty];
      } else {
        // 尝试直接使用数字或解析为数字
        const difficultyNum = typeof difficulty === 'number' ? difficulty : parseInt(difficulty);
        if (!isNaN(difficultyNum)) {
          card.difficulty = difficultyNum;
        }
      }
    }
    
    if (tags) card.tags = tags;

    card.updatedAt = Date.now();
    await card.save();

    res.json({
      message: '卡片更新成功',
      card
    });
  } catch (error) {
    console.error('更新知识卡片时出错:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

/**
 * @desc    获取卡片的练习题
 * @route   GET /api/cards/:id/exercises
 * @access  私有
 */
const getCardExercises = async (req, res) => {
  try {
    const { id } = req.params;
    
    // 查找卡片
    const card = await Card.findById(id);
    if (!card) {
      return res.status(404).json({ message: '卡片不存在' });
    }

    // 获取已有的练习题
    const exercises = await Exercise.find({ cardId: id });

    res.json(exercises);
  } catch (error) {
    console.error('获取卡片练习题时出错:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

/**
 * @desc    为卡片生成练习题
 * @route   POST /api/cards/:id/exercises/generate
 * @access  私有
 */
const generateCardExercises = async (req, res) => {
  try {
    const { id } = req.params;
    const { choiceCount = 1, fillCount = 1, codeCount = 0 } = req.body;
    
    // 查找卡片
    const card = await Card.findById(id);
    if (!card) {
      return res.status(404).json({ message: '卡片不存在' });
    }

    // 生成练习题
    const exercises = await ExerciseGenerator.generateExercises(card, {
      choiceCount: parseInt(choiceCount),
      fillCount: parseInt(fillCount),
      codeCount: parseInt(codeCount)
    });

    res.status(201).json({
      message: '练习题生成成功',
      exercises
    });
  } catch (error) {
    console.error('生成练习题时出错:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

/**
 * @desc    获取卡片的相关卡片
 * @route   GET /api/cards/:id/related
 * @access  私有
 */
const getRelatedCards = async (req, res) => {
  try {
    const { id } = req.params;
    
    // 查找卡片
    const card = await Card.findById(id);
    if (!card) {
      return res.status(404).json({ message: '卡片不存在' });
    }

    // 获取相关卡片
    const relatedCards = await Card.find({ _id: { $in: card.relatedCards } })
      .select('title content chapter difficulty tags');

    res.json(relatedCards);
  } catch (error) {
    console.error('获取相关卡片时出错:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

/**
 * @desc    获取所有章节
 * @route   GET /api/cards/chapters
 * @access  私有
 */
const getChapters = async (req, res) => {
  try {
    // 聚合所有不同的章节
    const chapters = await Card.aggregate([
      { $group: { _id: '$chapter', count: { $sum: 1 } } },
      { $sort: { _id: 1 } },
      { $project: { chapter: '$_id', count: 1, _id: 0 } }
    ]);

    res.json(chapters);
  } catch (error) {
    console.error('获取章节时出错:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

/**
 * @desc    获取所有标签
 * @route   GET /api/cards/tags
 * @access  私有
 */
const getTags = async (req, res) => {
  try {
    // 聚合所有不同的标签
    const tags = await Card.aggregate([
      { $unwind: '$tags' },
      { $group: { _id: '$tags', count: { $sum: 1 } } },
      { $sort: { count: -1 } },
      { $project: { tag: '$_id', count: 1, _id: 0 } }
    ]);

    res.json(tags);
  } catch (error) {
    console.error('获取标签时出错:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

module.exports = {
  getCards,
  getCardById,
  updateCard,
  getCardExercises,
  generateCardExercises,
  getRelatedCards,
  getChapters,
  getTags
}; 